/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.bingoogolapple.qrcode;

import com.bingoogolapple.qrcode.core.DeviceUtil;
import com.bingoogolapple.qrcode.core.LogUtil;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.window.dialog.ToastDialog;
import ohos.bundle.IBundleManager;

/**
 * 入口ability程序初始入口
 */
public class MainAbility extends Ability {
    private static final int MY_PERMISSIONS_REQUEST_CAMERA = 1;
    private String mAbilityName;
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_entry_layout);
        DeviceUtil.getDisplayAttributes(getContext());
        checkCameraPermission();
        initButtons();
    }

    private void initButtons() {
        Button zbarButton = (Button) findComponentById(ResourceTable.Id_enter_zbar);
        zbarButton.setClickedListener(new Component.ClickedListener() {
                    @Override
                    public void onClick(Component component) {
                        launchAbility("com.bingoogolapple.qrcode.ZbarAbility");

                    }
                });

        Button zxingButton = (Button)(findComponentById(ResourceTable.Id_enter_zxing));
        zxingButton.setClickedListener(new Component.ClickedListener() {
                    @Override
                    public void onClick(Component component) {
                        launchAbility("com.bingoogolapple.qrcode.ZxingAbility");
                    }
                });
    }

    private void launchAbility(String abilityName) {
        mAbilityName = abilityName;
        if (checkCameraPermission()) {
            startSampleAbility(abilityName);
        }
    }

    private void startSampleAbility(String abilityName) {
        Intent intent = new Intent();
        Operation operation = new Intent.OperationBuilder()
                .withDeviceId("")
                .withBundleName("com.bingoogolapple.qrcode")
                .withAbilityName(abilityName)
                .build();
        intent.setOperation(operation);
        startAbility(intent);
    }

    private boolean checkCameraPermission() {
        boolean isGranted = false;

        if (getContext().verifySelfPermission("ohos.permission.CAMERA") != IBundleManager.PERMISSION_GRANTED) {
            if (canRequestPermission("ohos.permission.CAMERA")) {
                isGranted = false;
                requestPermissionsFromUser(
                        new String[] {"ohos.permission.CAMERA"}, MY_PERMISSIONS_REQUEST_CAMERA);
            } else {
                isGranted = false;
                LogUtil.error("cannot request camera");
            }
        } else {
            isGranted = true;
            LogUtil.info("camera has been permitted");
        }

        return isGranted;
    }

    @Override
    public void onRequestPermissionsFromUserResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_CAMERA: {
                if (grantResults.length > 0
                        && grantResults[0] == IBundleManager.PERMISSION_GRANTED) {
                    LogUtil.info(  "camera is granted by user");
                    startSampleAbility(mAbilityName);
                } else {
                    LogUtil.error( "camera has been rejected by user");
                    new ToastDialog(getContext())
                            .setText("Please grant camera permission to use the QR Scanner")
                            .show();
                }
                return;
            }
            default:
                LogUtil.error( "invalid requestCode");
                return;
        }
    }
}
